import React, { Component } from "react";
import MyTable from "./MyTable";
import MyPrice from "./MyPrice";
export default class Five extends Component {
  constructor(props) {
    super(props);
    this.state = {
      books: [
        {
          id: 1,
          name: "算法导论",
          date: "2006-9",
          price: 85,
          count: 0,
        },
        {
          id: 2,
          name: "UNIX编程艺术",
          date: "2006-2",
          price: 59,
          count: 0,
        },
        {
          id: 3,
          name: "编程珠玑",
          date: "2008-10",
          price: 39,
          count: 0,
        },
        {
          id: 4,
          name: "代码大全",
          date: "2006-3",
          price: 128,
          count: 0,
        },
      ],
      countPrice: 0,
    };
  }

  render() {
    return (
      <div>
        {this.state.books.length ? this.renderTable() : this.renderEmpty()}
      </div>
    );
  }

  renderTable() {
    return (
      <div className="table-container">
        <div>
          {this.state.books.length ? (
            <MyTable
              books={this.state.books}
              changeCount={(type, index) => this.changeCountState(type, index)}
              removeBook={(index) => this.removeBook(index)}
            />
          ) : (
            <h2>当前购物车为空</h2>
          )}
        </div>
        <div>
          {this.state.books.length && (
            <MyPrice
              countPrice={() => this.computedPrice()}
              setPrice={() => this.setPrice()}
            />
          )}
        </div>
      </div>
    );
  }

  renderEmpty() {
    return (
      <div>
        <h2>购物车为空~</h2>
      </div>
    );
  }

  setPrice() {
    this.setState({
      countPrice: this.computedPrice(),
    });
  }

  // 计算总价格
  computedPrice() {
    let sum = 0;
    this.state.books.forEach((item) => {
      sum += item.price * item.count;
    });

    return sum;
  }

  // 修改数量
  changeCountState(type, index) {
    const newStateBooks = [...this.state.books];
    type === "add"
      ? newStateBooks[index].count++
      : newStateBooks[index].count--;
    this.setState({
      books: newStateBooks,
    });
  }

  // filter实现删除书籍
  removeBook(index) {
    this.setState({
      books: this.state.books.filter((item) => item.id != index),
    });
  }
}
